package mygame.TerrainGenerator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.util.BufferUtils;


public class MeshGenerator {

	public static Geometry generateTerrainFromHeightMap(HeightMap hm,int steps,float scale){
		int height = hm.getHeight()/steps;
		int width = hm.getWidth()/steps;
		Vector3f [] vertices = new Vector3f[width*height];
		Vector2f[] texCoord = new Vector2f[vertices.length];
		float texStepX = 1f/(width);
		float texStepZ = 1f/(height);		
		ArrayList<Integer> indexes = new ArrayList<>();
		
		for(int z=0;z<height;z+=1){
			int tz = z*steps;
			for(int x=0;x<width;x+=1){
				int tx = x*steps;
				Vector3f v = new Vector3f(tx, hm.getValue(tx, tz)*scale, tz);
				vertices[oneDFrom2D(z, height, x)] = v;
				texCoord[oneDFrom2D(z, height, x)] = new Vector2f(texStepX*x,texStepZ*z);
				if(z+1<height){
					if(x+1<width){
						indexes.add(oneDFrom2D(z, height, x));
						indexes.add(oneDFrom2D(z+1, height, x));
						indexes.add(oneDFrom2D(z, height, x+1));
						//int[] index = {z,x z+1,x z,x+1};
//						System.out.print("1");
					}
					if(x-1>=0){
						indexes.add(oneDFrom2D(z, height, x));
						indexes.add(oneDFrom2D(z+1, height, x-1));
						indexes.add(oneDFrom2D(z+1, height, x));
						//int[] index2 ={z,x z+1,x-1 z+1,x}
//						System.out.print("2");
					}
					//System.out.print("-");
				}
			}
//			System.out.println();
		}		
		Mesh mesh = new Mesh();
		mesh.setBuffer(Type.Position, 3, BufferUtils.createFloatBuffer(vertices));
		mesh.setBuffer(Type.TexCoord, 2, BufferUtils.createFloatBuffer(texCoord));		
		mesh.setBuffer(Type.Index,    3, BufferUtils.createIntBuffer(convertIntegers(indexes)));
		mesh.updateBound();
		Geometry geom = new Geometry("Terrain",mesh);
		geom.setLocalTranslation(-(hm.getWidth()/steps)/2, 0, -height/2);
		return geom;
	}
	
	private static int oneDFrom2D(int y,int height,int x){
		return y*height+x;
	}
	
	private static int[] convertIntegers(List<Integer> integers)
	{
	    int[] ret = new int[integers.size()];
	    Iterator<Integer> iterator = integers.iterator();
	    for (int i = 0; i < ret.length; i++)
	    {
	        ret[i] = iterator.next().intValue();
	    }
	    return ret;
	}
}
